<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="filter-tags" v-if="hasActiveFilters">
      <span class="filter-label">已选条件：</span>
      <el-tag
        v-if="query.status"
        closable
        @close="clearFilter('status')"
        size="small"
        class="filter-tag"
        :type="getStatusType(query.status)"
      >
        状态: {{ query.status }}
      </el-tag>
      <el-tag
        v-if="query.type"
        closable
        @close="clearFilter('type')"
        size="small"
        class="filter-tag"
      >
        类型: {{ getTypeLabel(query.type) }}
      </el-tag>
      <el-tag
        v-if="query.reason"
        closable
        @close="clearFilter('reason')"
        size="small"
        class="filter-tag"
      >
        原因: {{ query.reason }}
      </el-tag>
      <el-tag
        v-if="query.startDate || query.endDate"
        closable
        @close="clearDateFilter()"
        size="small"
        class="filter-tag"
      >
        举报时间: {{ query.startDate || "-" }} 至 {{ query.endDate || "-" }}
      </el-tag>
      <el-button type="primary" link @click="resetFilters" size="small"
        >清空全部</el-button
      >
    </div>

    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :viewFunc="handleView"
        :page-change="changePage"
        :loading="loading"
      >
        <template #status="{ rows }">
          <el-tag :type="getStatusType(rows.status)">{{ rows.status }}</el-tag>
        </template>

        <template #type="{ rows }">
          <el-tag :type="getTypeTagType(rows.type)">{{
            getTypeLabel(rows.type)
          }}</el-tag>
        </template>

        <template #operator="{ rows }">
          <div class="report-actions">
            <el-button type="primary" size="default" @click="handleView(rows)"
              >查看</el-button
            >
            <el-button
              v-if="rows.status === '待处理'"
              type="warning"
              size="default"
              @click="handleProcess(rows)"
              >处理</el-button
            >
          </div>
        </template>
      </TableCustom>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog
      title="举报详情"
      v-model="detailVisible"
      width="800px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="举报ID">{{
          currentReport._id
        }}</el-descriptions-item>
        <el-descriptions-item label="举报状态">
          <el-tag :type="getStatusType(currentReport.status)">
            {{ currentReport.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="举报类型">
          {{ getTypeLabel(currentReport.type) }}
        </el-descriptions-item>
        <el-descriptions-item label="举报原因">
          {{ currentReport.reason }}
        </el-descriptions-item>
        <el-descriptions-item label="举报时间">
          {{ formatDate(currentReport.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理时间" v-if="currentReport.handledAt">
          {{ formatDate(currentReport.handledAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理结果" v-if="currentReport.result">
          {{ currentReport.result }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 处理举报弹窗 -->
    <el-dialog
      title="处理举报"
      v-model="processState.visible"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @closed="handleProcessDialogClosed"
    >
      <el-form
        ref="processForm"
        :model="processState.form"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select
            v-model="processState.form.status"
            placeholder="请选择处理状态"
          >
            <el-option label="处理中" value="处理中" />
            <el-option label="已处理" value="已处理" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>
        </el-form-item>

        <el-form-item label="处理结果" prop="result">
          <el-input
            type="textarea"
            v-model="processState.form.result"
            :rows="3"
            placeholder="请输入处理结果说明"
          />
        </el-form-item>

        <el-form-item label="处理操作" prop="action">
          <el-select
            v-model="processState.form.action"
            placeholder="请选择处理操作"
            :disabled="!showActionSelect"
          >
            <el-option
              v-for="option in actionOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="processState.visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitProcess"
          :loading="processState.loading"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, computed } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import request from "@/utils/request";
import { FormOptionList } from "@/types/form-option";
import _ from "lodash";

export default {
  name: "system-report",
  setup() {
    // 查询相关
    const query = reactive({
      status: "",
      type: "",
      reason: "",
      startDate: "",
      endDate: "",
      sort: "createdAt",
      order: "desc",
    });

    const searchOpt = ref<FormOptionList[]>([
      {
        type: "select",
        label: "举报状态：",
        prop: "status",
        opts: [
          { label: "全部", value: "" },
          { label: "待处理", value: "待处理" },
          { label: "处理中", value: "处理中" },
          { label: "已处理", value: "已处理" },
          { label: "已驳回", value: "已驳回" },
        ],
      },
      {
        type: "select",
        label: "举报类型：",
        prop: "type",
        opts: [
          { label: "全部", value: "" },
          { label: "商品", value: "product" },
          { label: "用户", value: "user" },
          { label: "订单", value: "order" },
        ],
      },
      {
        type: "input",
        label: "举报原因：",
        prop: "reason",
        placeholder: "输入举报原因关键词",
      },
      {
        type: "datepicker",
        label: "举报时间：",
        prop: "datepicker",
        format: "YYYY-MM-DD",
        onChange: (val: [string, string]) => {
          if (val) {
            query.startDate = val[0];
            query.endDate = val[1];
          } else {
            query.startDate = "";
            query.endDate = "";
          }
        },
      },
    ]);

    // 表格相关
    const loading = ref(false);
    const columns = ref([
      { type: "index", label: "序号", width: 55, align: "center" },
      { prop: "_id", label: "举报ID", width: 120 },
      { prop: "type", label: "举报类型", width: 100, slotName: "type" },
      { prop: "reason", label: "举报原因", minWidth: 200 },
      { prop: "status", label: "状态", width: 100, slotName: "status" },
      { prop: "formattedDate", label: "举报时间", width: 180 },
      { prop: "operator", label: "操作", width: 180, slotName: "operator" },
    ]);

    // 状态标签类型
    const getStatusType = (status: string) => {
      const typeMap: Record<string, string> = {
        待处理: "warning",
        处理中: "info",
        已处理: "success",
        已驳回: "danger",
      };
      return typeMap[status] || "";
    };

    // 举报类型标签
    const getTypeLabel = (type: string) => {
      const labelMap: Record<string, string> = {
        product: "商品",
        user: "用户",
        order: "订单",
      };
      return labelMap[type] || type;
    };

    const getTypeTagType = (type: string) => {
      const typeMap: Record<string, string> = {
        product: "success",
        user: "warning",
        order: "info",
      };
      return typeMap[type] || "";
    };

    // 处理操作选项
    const actionOptions = computed(() => {
      const currentType = currentReport.value?.type;
      if (!currentType) return [];

      const options = {
        user: [
          { label: "封禁用户", value: "ban" },
          { label: "禁言用户", value: "mute" },
        ],
        product: [{ label: "下架商品", value: "remove" }],
        order: [{ label: "取消订单", value: "cancel" }],
      };

      return options[currentType] || [];
    });

    // 是否显示操作选择
    const showActionSelect = computed(() => {
      return processState.form.status === "已处理";
    });

    // 分页相关
    const page = reactive({
      index: 1,
      size: 10,
      total: 0,
    });

    // 数据获取
    const tableData = ref<any[]>([]);
    const getData = async () => {
      try {
        loading.value = true;
        const params = {
          page: page.index,
          limit: page.size,
          ...query,
        };

        const res = await request.get("/api/reports", params);
        if (res.success) {
          tableData.value = res.data.reports.map((report: any) => ({
            ...report,
            formattedDate: formatDate(report.createdAt),
          }));
          page.total = res.data.total;
        }
      } catch (error) {
        console.error("获取举报列表失败:", error);
        ElMessage.error("获取数据失败");
      } finally {
        loading.value = false;
      }
    };

    // 详情弹窗
    const detailVisible = ref(false);
    const currentReport = ref<any>({});

    const handleView = (row: any) => {
      currentReport.value = row;
      detailVisible.value = true;
    };

    // 处理弹窗状态管理
    const processState = reactive({
      visible: false,
      loading: false,
      currentReport: null as any,
      form: {
        status: "",
        result: "",
        action: "",
      },
    });

    const handleProcess = (row: any) => {
      processState.currentReport = _.cloneDeep(row);
      processState.form = {
        status: row.status || "",
        result: "",
        action: "",
      };
      processState.visible = true;
    };

    const handleProcessDialogClosed = () => {
      processState.currentReport = null;
      processState.form = { status: "", result: "", action: "" };
    };

    const submitProcess = async () => {
      if (!processState.currentReport) {
        ElMessage.error("当前举报记录已失效");
        return;
      }

      try {
        processState.loading = true;
        const { status, result, action } = processState.form;

        const res = await request.put(
          `/api/reports/${processState.currentReport._id}`,
          {
            status,
            result,
            action,
          }
        );

        if (res.success) {
          ElMessage.success("处理成功");
          processState.visible = false;
          getData();
        }
      } catch (error) {
        console.error("处理失败:", error);
        ElMessage.error("处理失败");
      } finally {
        processState.loading = false;
      }
    };

    // 其他工具方法
    const formatDate = (dateStr: string) => {
      if (!dateStr) return "-";
      try {
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")} ${String(
          date.getHours()
        ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
      } catch (e) {
        return "-";
      }
    };

    // 筛选相关
    const hasActiveFilters = computed(() => {
      return (
        !!query.status ||
        !!query.type ||
        !!query.reason ||
        !!query.startDate ||
        !!query.endDate
      );
    });

    const clearFilter = (field: string) => {
      query[field] = "";
      getData();
    };

    const clearDateFilter = () => {
      query.startDate = "";
      query.endDate = "";
      getData();
    };

    const resetFilters = () => {
      Object.keys(query).forEach((key) => {
        if (key !== "sort" && key !== "order") {
          query[key] = "";
        }
      });
      getData();
    };

    const handleSearch = () => {
      page.index = 1;
      getData();
    };

    const changePage = (val: number) => {
      page.index = val;
      getData();
    };

    // 修改表单验证规则定义
    const processRules = reactive({
      status: [
        { required: true, message: "请选择处理状态", trigger: "change" },
      ],
      result: [
        { required: true, message: "请输入处理结果说明", trigger: "blur" },
      ],
      action: [
        // 添加action字段的验证规则
        {
          required: true,
          message: "请选择处理操作",
          trigger: "change",
          validator: (rule: any, value: any, callback: any) => {
            if (processState.form.status === "已处理" && !value) {
              callback(new Error("处理状态为已处理时必须选择操作"));
            } else {
              callback();
            }
          },
        },
      ],
    });

    // 初始化
    getData();

    return {
      query,
      searchOpt,
      columns,
      tableData,
      loading,
      page,
      detailVisible,
      currentReport,
      processState,
      processRules,
      actionOptions,
      showActionSelect,
      hasActiveFilters,
      getStatusType,
      getTypeLabel,
      getTypeTagType,
      handleView,
      handleProcess,
      submitProcess,
      handleSearch,
      changePage,
      clearFilter,
      clearDateFilter,
      resetFilters,
      formatDate,
      handleProcessDialogClosed,
    };
  },
};
</script>

<style scoped>
.container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-tags {
  margin: 10px 0;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
  color: #606266;
}

.filter-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

.report-actions {
  display: flex;
  gap: 8px;
}
</style>
